<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">{{ templeInfo.name }} - 管理</span>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <!-- 会员管理 -->
        <el-tab-pane label="会员管理" name="members">
          <MemberManagement 
            :temple-id="templeId"
            :positions="positions"
            :clan-members="clanMembers"
            @update:members="handleMembersUpdate"
          />
        </el-tab-pane>

        <!-- 职位管理 -->
        <el-tab-pane label="职位管理" name="positions">
          <PositionManagement 
            :members="members"
            @update:positions="handlePositionsUpdate"
          />
        </el-tab-pane>

        <!-- 宗亲会信息 -->
        <el-tab-pane label="宗亲会信息" name="info">
          <TempleInfoManagement 
            :temple-id="templeId"
            :is-view-mode="false"
            @update:temple-info="handleTempleInfoUpdate"
          />
        </el-tab-pane>

        <!-- 入会申请 -->
        <el-tab-pane label="入会申请" name="applications">
          <ApplicationManagement :applications="applications" />
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 申请详情对话框 -->
    <el-dialog v-model="applicationDetailVisible" :title="currentApplication?.status === '待审核' ? '入会申请审核' : '入会申请详情'"
      width="60%" top="5vh" append-to-body>
      <el-descriptions v-if="currentApplication" :column="2" border>
        <el-descriptions-item label="申请状态">
          <el-tag
            :type="currentApplication.status === '待审核' ? 'warning' : (currentApplication.status === '已通过' ? 'success' : 'danger')">
            {{ currentApplication.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ currentApplication.applyDate }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ currentApplication.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ currentApplication.gender }}</el-descriptions-item>
        <el-descriptions-item label="出生年月">{{ currentApplication.birthDate }}</el-descriptions-item>
        <el-descriptions-item label="籍贯">{{ currentApplication.nativePlace }}</el-descriptions-item>
        <el-descriptions-item label="民族">{{ currentApplication.ethnicity }}</el-descriptions-item>
        <el-descriptions-item label="文化程度">{{ currentApplication.education }}</el-descriptions-item>
        <el-descriptions-item label="政治面貌">{{ currentApplication.politicalStatus }}</el-descriptions-item>
        <el-descriptions-item label="专长">{{ currentApplication.specialty }}</el-descriptions-item>
        <el-descriptions-item label="推荐人">{{ currentApplication.recommender }}</el-descriptions-item>
        <el-descriptions-item label="手机号码">{{ currentApplication.phone }}</el-descriptions-item>
        <el-descriptions-item label="身份证号码">{{ currentApplication.idCard }}</el-descriptions-item>
        <el-descriptions-item label="通讯地址">{{ currentApplication.address }}</el-descriptions-item>
        <el-descriptions-item label="会员类型">
          {{ {
            'A': '文史会员',
            'B': '联盟成员',
            'C': '联盟企业'
          }[currentApplication.memberType] }}
        </el-descriptions-item>
        <el-descriptions-item label="拟任职务" v-if="currentApplication.memberType === 'A'">
          {{ currentApplication.proposedPosition }}
        </el-descriptions-item>
        <template v-if="currentApplication.memberType === 'B' || currentApplication.memberType === 'C'">
          <el-descriptions-item label="企业名称">{{ currentApplication.companyName }}</el-descriptions-item>
          <el-descriptions-item label="职务">{{ currentApplication.position }}</el-descriptions-item>
          <el-descriptions-item label="注册资金">{{ currentApplication.registeredCapital }}万元</el-descriptions-item>
          <el-descriptions-item label="企业地址">{{ currentApplication.companyAddress }}</el-descriptions-item>
          <el-descriptions-item label="经营范围" :span="2">{{ currentApplication.businessScope }}</el-descriptions-item>
        </template>
        <el-descriptions-item label="缴费金额">{{ currentApplication.paymentAmount }}元</el-descriptions-item>
        <el-descriptions-item label="缴费时间">{{ currentApplication.paymentTime }}</el-descriptions-item>
      </el-descriptions>

      <div class="image-preview" v-if="currentApplication">
        <div class="preview-item">
          <h4>个人照片</h4>
          <el-image :src="currentApplication.photoUrl" :preview-src-list="[currentApplication.photoUrl]" fit="cover"
            style="width: 100px; height: 100px" />
        </div>
        <div class="preview-item">
          <h4>支付凭证</h4>
          <el-image :src="currentApplication.paymentProofUrl" :preview-src-list="[currentApplication.paymentProofUrl]"
            fit="cover" style="width: 100px; height: 100px" />
        </div>
      </div>

      <div v-if="currentApplication?.status === '待审核'" class="review-form">
        <el-divider>审核意见</el-divider>
        <el-form :model="reviewForm" label-width="100px">
          <el-form-item label="审核备注">
            <el-input v-model="reviewForm.remarks" type="textarea" :rows="3" placeholder="请输入审核意见（选填）" />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <template v-if="currentApplication?.status === '待审核'">
            <el-button @click="applicationDetailVisible = false">取消</el-button>
            <el-button type="danger" @click="handleReject(currentApplication.id)">拒绝</el-button>
            <el-button type="primary" @click="handleApprove(currentApplication.id)">通过</el-button>
          </template>
          <template v-else>
            <el-button @click="applicationDetailVisible = false">关闭</el-button>
          </template>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import TempleAPI from "@/api/genealogy/temple.api"


import ClanMemberAPI from "@/api/clanMember/clanMember"
// 获取路由传递过来的参数id
import AmapPicker from "@/components/Map/AmapPicker.vue"
import WangEditor from "@/components/WangEditor/index.vue"
import SingleImageUpload from "@/components/Upload/SingleImageUpload.vue"
import ApplicationManagement from "./components/ApplicationManagement.vue"
import PositionManagement from "./components/PositionManagement.vue"
import MemberManagement from "./components/MemberManagement.vue"
import TempleInfoManagement from "./components/TempleInfoManagement.vue"

const route = useRoute()
const router = useRouter()
const templeId = route.query.id
const activeTab = ref('members')

// 宗亲会信息
const templeInfo = ref({
  name: '江西博阳李氏宗亲会',
  location: '福建省厦门市思明区某某路123号',
  history: '这是一个具有悠久历史的宗亲会，始建于1900年，经过多代人的传承和发展，现已成为本地区最具影响力的宗亲组织之一。宗亲会致力于弘扬传统文化，增进宗亲情谊，促进社会和谐。',
  qrcodeUrl: '/src/assets/logo.png',
  longitude: 118.0894,
  latitude: 24.4798
})

// 会员管理
const members = ref([])



// 职位管理
const positions = ref([])



// 入会申请
const applications = ref([
  {
    id: 1,
    name: '郑一',
    gender: '男',
    birthDate: '1990-01-01',
    nativePlace: '江西省上饶市',
    ethnicity: '汉族',
    education: '本科',
    politicalStatus: '群众',
    specialty: '企业管理',
    recommender: '李四',
    phone: '13900139001',
    idCard: '360123199001011234',
    address: '江西省上饶市信州区',
    memberType: 'A',
    proposedPosition: '会员',
    paymentAmount: 500,
    paymentTime: '2023-05-01',
    paymentProofUrl: '/path/to/proof1.jpg',
    photoUrl: '/path/to/photo1.jpg',
    reason: '祖籍在此，希望加入宗亲会了解家族历史',
    status: '待审核',
    applyDate: '2023-05-01'
  },
  {
    id: 2,
    name: '郑二',
    gender: '女',
    birthDate: '1985-06-15',
    nativePlace: '江西省上饶市',
    ethnicity: '汉族',
    education: '硕士',
    politicalStatus: '中共党员',
    specialty: '金融投资',
    recommender: '王五',
    phone: '13900139002',
    idCard: '360123198506151234',
    address: '江西省上饶市广信区',
    memberType: 'B',
    companyName: '上饶投资有限公司',
    position: '总经理',
    registeredCapital: 1000,
    companyAddress: '江西省上饶市广信区某某路123号',
    businessScope: '投资管理、资产管理、企业管理咨询',
    paymentAmount: 1000,
    paymentTime: '2023-04-15',
    paymentProofUrl: '/path/to/proof2.jpg',
    photoUrl: '/path/to/photo2.jpg',
    reason: '寻根问祖，希望能与宗亲们交流',
    status: '已通过',
    applyDate: '2023-04-15'
  }
])



const totalMembers = ref(0)

// 返回详情页
const handleBack = () => {
  router.push({ name: 'TempleDetail', params: { id: templeId } })
}

// 会员管理方法
const handleMembersUpdate = (updatedMembers) => {
  members.value = updatedMembers
}

// 职位管理方法
const handlePositionsUpdate = (updatedPositions) => {
  positions.value = updatedPositions
}

// 宗亲会信息管理方法
const handleTempleInfoUpdate = (updatedTempleInfo) => {
  templeInfo.value = updatedTempleInfo
}

// 申请管理方法
const applicationDetailVisible = ref(false)
const currentApplication = ref(null)
const reviewForm = ref({
  remarks: ''
})

// 审核申请
const handleReview = (row) => {
  currentApplication.value = row
  reviewForm.value.remarks = ''
  applicationDetailVisible.value = true
}

// 通过申请
const handleApprove = (id) => {
  const application = applications.value.find(item => item.id === id)
  if (!application) return

  ElMessageBox.confirm(
    `确定通过 ${application.name} 的入会申请吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    const index = applications.value.findIndex(item => item.id === id)
    if (index !== -1) {
      applications.value[index].status = '已通过'
      applications.value[index].reviewRemarks = reviewForm.value.remarks

      // 添加为新会员
      const newId = Math.max(...members.value.map(item => item.id), 0) + 1
      members.value.push({
        id: newId,
        name: application.name,
        gender: application.gender,
        birthDate: application.birthDate,
        nativePlace: application.nativePlace,
        ethnicity: application.ethnicity,
        education: application.education,
        politicalStatus: application.politicalStatus,
        specialty: application.specialty,
        phone: application.phone,
        idCard: application.idCard,
        address: application.address,
        position: '会员',
        joinDate: new Date().toISOString().split('T')[0],
        memberType: application.memberType,
        photoUrl: application.photoUrl,
        email: '',
        familyRelation: '',
        remarks: `由${application.recommender}推荐入会${reviewForm.value.remarks ? '，审核备注：' + reviewForm.value.remarks : ''}`
      })

      ElMessage.success('已通过申请')
      applicationDetailVisible.value = false
    }
  }).catch(() => { })
}

// 拒绝申请
const handleReject = (id) => {
  const application = applications.value.find(item => item.id === id)
  if (!application) return

  ElMessageBox.confirm(
    `确定拒绝 ${application.name} 的入会申请吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = applications.value.findIndex(item => item.id === id)
    if (index !== -1) {
      applications.value[index].status = '已拒绝'
      applications.value[index].reviewRemarks = reviewForm.value.remarks
      ElMessage.success('已拒绝申请')
      applicationDetailVisible.value = false
    }
  }).catch(() => { })
}






// 宗亲会员列表数据
const clanMembers = ref([])

// 获取宗亲会员列表
const getMemberListS = async () => {
  try {
    const response = await ClanMemberAPI.getMemberListS()
    clanMembers.value = response || []
    console.log('宗亲会员列表:', clanMembers.value)
  } catch (error) {
    console.error('获取宗亲会员列表失败:', error)
    ElMessage.error('获取宗亲会员列表失败')
  }
}




// 监听tab切换，切换到“宗亲会信息”时再初始化地图
watch(activeTab, (val) => {
  if (val === 'info') {
    nextTick(() => {
      setTimeout(() => {
        if (window.AMap) {
          initMap()
        } else {
          loadAMap().then(() => initMap())
        }
      }, 500)
    })
  }
})
// 组件挂载后加载地图
onMounted(() => {
  // 获取宗亲会员列表
  getMemberListS()
  
  nextTick(() => {
    setTimeout(() => {
      if (window.AMap) {
        initMap()
      } else {
        loadAMap().then(() => initMap())
      }
    }, 500)
  })
})
</script>

<style scoped>

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 24px;
  font-weight: bold;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.section {
  margin-top: 30px;
}

.image-preview {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.preview-item {
  text-align: center;
}

.preview-item h4 {
  margin-bottom: 10px;
}

.review-form {
  margin-top: 20px;
}



.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 5px;
}






</style>
